<template>
	<el-dialog
		width="99%"
		:close-on-click-modal="false"
		v-model="dialogVisible"
		:title="state.title + ' ' + state.row.outboundCode"
		destroy-on-close
		:before-close="handleClose"
	>
		<el-checkbox label="同步消耗辅料" v-model="state.form.type" @change="changeTableType"></el-checkbox>
		<table-layout
			v-if="state.refreshTable"
			ref="dataTableRef"
			:isPage="false"
			row-key="id"
			:tree-props="{ children: 'itemList' }"
			:query-form="{}"
			min-height="50vh"
			:header-cell-style="{ color: '#000' }"
			:row-class-name="tableRowClassName"
			:default-expand-all="state.form.type"
			border
			:data="state.form.infoData"
		>
			<template v-slot:tableLayout>
				<el-table-column label="公司主体" prop="companyName" min-width="150px"></el-table-column>
				<el-table-column label="团队" prop="teamName" min-width="100px"></el-table-column>
				<el-table-column label="备货区域" prop="stockupAreaName" min-width="110px"></el-table-column>
				<el-table-column label="备货平台" prop="stockupPlatformName" min-width="110px"></el-table-column>
				<el-table-column label="仓库" prop="whNameFrom" min-width="100px"></el-table-column>
				<el-table-column label="产品图片" prop="" min-width="90px">
					<template v-slot="scope">
						<ewt-image :url="scope.row.picUrl" style="width: 36px; height: 36px; object-fit: contain; display: block; cursor: pointer" />
						<!-- <div v-else class="non-pic">无图</div> -->
					</template>
				</el-table-column>
				<el-table-column label="产品名称/SKU" prop="value" min-width="120px">
					<template v-slot="scope">
						<div>{{ scope.row.skuName || '--' }}</div>
						<div style="margin-top: 16px">{{ scope.row.skuCode || '--' }}</div>
					</template>
				</el-table-column>
				<el-table-column label="待拣产品质量" prop="value" min-width="120px">
					<template v-slot="scope">
						<div>{{ scope.row.qualityType === '1' ? '良品' : scope.row.qualityType === '2' ? '次品' : '' }}</div>
					</template>
				</el-table-column>
				<el-table-column label="待拣货数量" prop="pendPickQty" min-width="120px"></el-table-column>
				<el-table-column label="拣货库位" prop="positionId" min-width="160px" fixed="right">
					<template #header>
						<span class="table-require"> 拣货库位 </span>
					</template>
					<template v-slot="scope">
						<template v-if="scope.row.pickBatchDtoList">
							<div v-for="(item, ind) in scope.row.pickBatchDtoList" :key="item.id" class="add-pick">
								<div style="width: 40px; text-align: right">
									<el-icon style="margin-right: 6px" v-if="scope.row.pickBatchDtoList.length > 1" @click="scope.row.pickBatchDtoList.splice(ind, 1)">
										<Minus />
									</el-icon>
									<el-icon v-if="ind === scope.row.pickBatchDtoList.length - 1" @click="scope.row.pickBatchDtoList.push({})"><Plus /></el-icon>
								</div>
								<el-select
									class="only-form"
									v-model="item.positionId"
									placeholder="请选择库位"
									@focus="getPositionList(scope.row, item)"
									@change="changePosition(scope.row, item)"
								>
									<el-option
										v-for="position in item.positionList"
										:key="position.positionId"
										:label="position.positionCode"
										:value="position.positionId"
										:disabled="Array.from(scope.row.pickBatchDtoList, ({ positionId }) => positionId).includes(position.positionId)"
									></el-option>
								</el-select>
							</div>
						</template>
					</template>
				</el-table-column>
				<el-table-column label="拣货批次" prop="batchId" min-width="140px" fixed="right">
					<template #header>
						<span class="table-require"> 拣货批次 </span>
					</template>
					<template v-slot="scope">
						<template v-if="scope.row.pickBatchDtoList">
							<div v-for="item in scope.row.pickBatchDtoList" :key="item.id" class="add-pick">
								<el-select
									v-model="item.batchId"
									placeholder="请选择批次"
									@focus="getPositionList(scope.row, item)"
									@change="changeBatch(scope.row, item)"
								>
									<el-option
										v-for="batch in scope.row.batchSelectList"
										:key="batch.batchId"
										:label="batch.batchCode"
										:value="batch.batchId"
									></el-option>
								</el-select>
							</div>
						</template>
					</template>
				</el-table-column>
				<el-table-column label="拣货数量" prop="pickQty" min-width="160px" fixed="right">
					<template #header>
						<span class="table-require"> 拣货数量 </span>
					</template>
					<template v-slot="scope">
						<template v-if="scope.row.pickBatchDtoList">
							<div style="display: flex; align-items: center; gap: 10px">
								<div style="width: calc(100% - 60px)">
									<div v-for="item in scope.row.pickBatchDtoList" :key="item.id" class="add-pick">
										<el-input
											v-model="item.pickQty"
											oninput="value=value.replace(/^\D*(\d{0,9}(?:)?).*$/g,'$1')"
											@blur="
												item.pickQty = Number($event.target.value);
												judgeOtySum(scope.row, item);
											"
											placeholder="拣货数量"
										></el-input>
									</div>
								</div>
								<!-- 删除 -->
								<Delete
									@click="delAux(scope.row, scope.$index)"
									v-if="!scope.row.itemList"
									style="width: 1.2em; height: 1.2em; margin-right: 8px; cursor: pointer; color: #c45656"
								/>
							</div>
						</template>
					</template>
				</el-table-column>
			</template>
		</table-layout>

		<template #footer>
			<el-button @click="handleClose">取消</el-button>
			<el-button class="ml10" type="primary" @click="toSaveOPick">完成拣货</el-button>
		</template>
	</el-dialog>
</template>
<script setup lang="ts" name="orderPickingDialog">
import { pickOutbound, outboundPickBatch, completePick } from '../api.ts';
import { ElMessage, ElMessageBox } from 'element-plus';
const emit = defineEmits(['refresh']);
const state = reactive({
	title: '拣货',
	refreshTable: true,
	id: '',
	row: {},
	form: {
		type: false,
		infoData: [],
	},
	initData: {},
	unPickedVoList: [],
});
const dialogVisible = ref(false);
const dataTableRef = ref();
const judgeOtySum = (row, item) => {
	let sum = 0;
	row.pickBatchDtoList.forEach((item) => {
		if (item.pickQty > item.maxPickQty) {
			ElMessage({
				message: '拣货数量不能大于当前库存可用量',
				type: 'error',
			});
			item.pickQty = item.maxPickQty;
		} else {
			sum += Number(item.pickQty);
		}
	});
	if (sum > row.pendPickQty) {
		ElMessage({
			message: '拣货数量总和不可大于待拣货数量',
			type: 'error',
		});
		item.pickQty = '';
	}
};
const getPositionList = async (row, item) => {
	if (!row.batchSelectList) {
		const { data } = await outboundPickBatch({ id: row.outboundItemId, skuId: row.skuId });
		row.batchSelectList = data;
	}
	item.positionList = [];
	row.batchSelectList.forEach((it) => {
		if (!item.batchId) {
			item.positionList = [...item.positionList, ...it.positionList];
		} else {
			if (it.batchId === item.batchId) {
				item.positionList = it.positionList;
			}
		}
	});
};

const changeBatch = (row, item) => {
	let batch = row.batchSelectList.filter((i) => {
		return i.batchId === item.batchId;
	});

	item.batchCode = batch[0].batchCode;
	let position = batch[0].positionList.filter((n) => {
		return n.positionId === item.positionId;
	});
	if (position.length === 0) {
		item.positionId = '';
		item.positionCode = '';
		item.pickQty = '';
	}
};
const changePosition = (row, item) => {
	let position = item.positionList.filter((i) => {
		return i.positionId === item.positionId;
	});
	item.positionCode = position[0].positionCode;
	item.pickQty = position[0].pickQty;
	item.maxPickQty = position[0].pickQty;
};
// 切换
const changeTableType = () => {
	state.refreshTable = false;
	nextTick(() => {
		state.refreshTable = true;
	});
};
// 删除
const delAux = (row, ind) => {
	state.form.infoData.forEach((item) => {
		if (item.skuCode === row.parentSkuCode) {
			item.itemList.splice(ind - 1, 1);
		}
	});
};
// 打开弹窗
const openDialog = async (row) => {
	try {
		state.id = row.id;
		state.row = row;
		const { data } = await pickOutbound(state.id);
		state.form.infoData = JSON.parse(JSON.stringify(data.pickedVoList));
		state.initData = JSON.parse(JSON.stringify(data));
		state.form.infoData.forEach((item) => {
			if (!item.pickBatchDtoList || item.pickBatchDtoList.length === 0) {
				item.pickBatchDtoList = [{}];
			} else {
				item.pickBatchDtoList.forEach((it) => {
					if (it.batchId || it.positionId) {
						getPositionList(item, it);
					}
				});
			}
			if (item.itemList?.length > 0) {
				item.itemList.forEach((itemListIt) => {
					itemListIt.outboundItemId = item.outboundItemId;
					if (!itemListIt.pickBatchDtoList || itemListIt.pickBatchDtoList.length === 0) {
						itemListIt.pickBatchDtoList = [{}];
					}
				});
			}
			if (!item.itemList) {
				item.itemList = [];
			}
		});
		nextTick(() => {
			dialogVisible.value = true;
		});
	} catch (error) {
		ElMessage({
			message: error.msg,
			type: 'error',
		});
	}
};

// 关闭弹窗
const handleClose = () => {
	dialogVisible.value = false;
};
const tableRowClassName = ({ row, rowIndex }) => {
	if (row.itemList) {
		return 'row-header';
	}
	return '';
};
const toValidate = () => {
	return new Promise((resolve, reject) => {
		state.form.infoData.map((item) => {
			state.unPickedVoList = [];
			item.itSum = 0;
			item.pickBatchDtoList?.forEach((it) => {
				if (!it.batchId || !it.positionId || !it.pickQty) {
					reject({ msg: '数据未填写完整,且拣货数量需大于0' });
					return false;
				}
				if (it.pickQty) {
					item.itSum += it.pickQty;
					if (item.itSum > item.pendPickQty) {
						reject({ msg: '拣货数量总和不可大于待拣货数量' });
					} else if (item.itSum < item.pendPickQty) {
						state.unPickedVoList.push({
							outboundItemId: item.outboundItemId,
							unPickedQty: Number(item.pendPickQty) - Number(item.itSum),
						});
					}
				}
			});
			if (state.form.type) {
				item.itemList.map((child) => {
					let childItSum = 0;
					child.pickBatchDtoList?.forEach((it) => {
						if (!it.batchId || !it.positionId || !it.pickQty) {
							reject({ msg: '辅料数据未填写完整,且拣货数量需大于0' });
						}
						if (it.pickQty) {
							childItSum += it.pickQty;
							if (childItSum > child.pendPickQty) {
								reject({ msg: '拣货数量总和不可大于待拣货数量' });
							}
						}
					});
				});
			}
		});
		resolve(true);
	});
};
const toSaveOPick = async () => {
	try {
		await toValidate();
		let data = {
			outboundId: state.initData.outboundId,
			pickedVoList: JSON.parse(JSON.stringify(state.form.infoData)),
			unPickedVoList: state.unPickedVoList,
		};
		data.pickedVoList.forEach((item) => {
			item.pendPickQty = item.itSum;
		});
		if (!state.form.type) {
			data.pickedVoList.forEach((item) => {
				item.itemList = [];
			});
		}
		if (data.unPickedVoList.length >= 1) {
			ElMessageBox.confirm('系统会自动将本次拣货的货物生成一个新出库单剩余未拣货数量会在原出库单上更新', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			}).then(() => {
				// console.log(data);
				toCompletePick(data);
			});
		} else {
			// console.log(data);
			toCompletePick(data);
		}
	} catch (error) {
		ElMessage({
			message: error.msg,
			type: 'error',
		});
	}
};
const toCompletePick = (data) => {
	completePick(data)
		.then((res) => {
			ElMessage({
				message: res.msg || '拣货成功',
				type: 'success',
			});
			handleClose();
			emit('refresh');
		})
		.catch((error) => {
			ElMessage({
				message: error.msg,
				type: 'error',
			});
		});
};
defineExpose({
	openDialog,
});
</script>
<style scoped>
:deep(.el-table .row-header td) {
	background-color: #f5f7fa !important;
}
:deep(.el-table [class*='el-table__row--level'] .el-table__expand-icon) {
	display: none;
}
.non-pic {
	background: rgba(11, 16, 25, 0.05);
	border: 1px solid rgba(0, 0, 0, 0.03);
	color: rgba(11, 16, 25, 0.12);
	border-radius: 2px;
	display: flex;
	-webkit-box-pack: center;
	-ms-flex-pack: center;
	justify-content: center;
	-webkit-box-align: center;
	-ms-flex-align: center;
	align-items: center;
	width: 36px;
	height: 36px;
	line-height: 36px;
	text-align: center;
}
.table-require::before {
	content: '*';
	color: #e52e2e;
	margin-right: 4px;
}
.add-pick {
	display: flex;
	align-items: center;
	gap: 6px;
	margin: 6px 0;
}
.add-pick .only-form {
	width: calc(100% - 40px) !important;
}
.add-pick i {
	cursor: pointer;
}
.novali :deep(.el-input__wrapper) {
	border: 1px solid red !important;
}
</style>
